/*
    通用功能类，与业务无关的实现
*/
#ifndef __M_UTIL_H__
#define __M_UTIL_H__

#include <time.h>
//#include <unistd.h>
#include <string>
#include <sys/stat.h>

class Date
{
public:
    static size_t now()
    {
        return (size_t)time(nullptr);
    }
};

class File
{
public:
    static bool exists(const std::string& name)
    {
        //return access(name.c_str(), F_OK);  //不能跨平台
        struct stat st;
        return stat(name.c_str(), &st) == 0;
    }

    // ./a/bc/source.cc => ./a/bc/
    static std::string path(const std::string& pathname)
    {
        if (pathname.empty())
            return ".";
        // 找/或 ‘\’
        size_t pos = pathname.find_last_of("/\\");
        if (pos == std::string::npos)
        {
            // 当前目录
            return ".";
        }

        return pathname.substr(0, pos + 1);
    }

    static void create_directory(const std::string& pathname)
    {
        // ./acc/ab/a.txt 目录需要一级一级创建下去，要有ab，先有acc
        if (pathname.empty())
        {
            return;
        }

        if (exists(pathname))
        {
            return;
        }

        size_t pos, idx = 0;
        while (idx < pathname.size())
        {
            pos = pathname.find_first_of("/\\", idx);
            if (pos == std::string::npos)
            {
                mkdir(pathname.c_str(), 0755);
            }

            // 截取/前的目录
            std::string parent_dir = pathname.substr(0, pos + 1);
            if (exists(parent_dir) == true)
            {
                idx = pos + 1;
                continue;
            }
            mkdir(parent_dir.c_str(), 0777);
            idx = pos + 1;
        }
    }
};
#endif